<template>
  <div>
    <el-page-header content="产品列表" icon="" title="产品管理" />

    <el-card style="margin-top: 20px; height: calc(100vh - 150px)">
      <div class="search-box">
        <el-input
          placeholder="请输入搜索内容"
          v-model="tableForm.searchValue"
          style="width: 300px; height: 35px"
          @keyup.enter="handleSearch"
        >
          <template #suffix>
            <Search class="search-icon" @click="handleSearch" />
          </template>
        </el-input>
      </div>

      <el-table
        :data="tableData"
        :default-sort="{
          prop: tableForm.sortField,
          order: processOrder(tableForm.sortOrder),
        }"
        @sort-change="changeTableSort"
      >
        <el-table-column prop="name" label="产品图片" width="80">
          <template #default="scope">
            <el-avatar
              v-if="scope.row.cover"
              :src="`${store.state.API_BASE_URL}${scope.row.cover}`"
            />
            <el-avatar
              v-else
              :src="`${store.state.API_BASE_URL}/images/defaultUserImg.png`"
            />
          </template>
        </el-table-column>

        <el-table-column prop="title" label="产品名称" sortable="custom">
          <template #default="scope">
            <span class="to-ellipsis" :title="scope.row.title">
              {{ scope.row.title }}
            </span>
          </template>
        </el-table-column>

        <el-table-column prop="introduction" label="简要描述" sortable="custom">
          <template #default="scope">
            <span class="to-ellipsis" :title="scope.row.introduction">
              {{ scope.row.introduction }}
            </span>
          </template>
        </el-table-column>

        <el-table-column prop="createdAt" label="创建时间" sortable="custom">
        </el-table-column>

        <el-table-column prop="updatedAt" label="更新时间" sortable="custom">
        </el-table-column>

        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template v-slot="scope">
            <!-- 编辑 -->
            <el-button
              circle
              :icon="Edit"
              @click="handleEdit(scope.row)"
            ></el-button>
            <!-- 删除 -->
            <el-popconfirm
              title="你确定要删除吗?"
              confirmButtonText="确定"
              cancelButtonText="取消"
              @confirm="handleDelete(scope.row)"
            >
              <template #reference>
                <el-button circle :icon="Delete" type="danger"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        style="height: 30px; justify-content: center"
        background
        layout="total, prev, pager, next, sizes, jumper"
        :page-size="tableForm.limit"
        :page-sizes="[1, 5, 10, 20]"
        :current-page="tableForm.pageNo"
        :total="total"
        :hide-on-single-page="total <= 0"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
      >
      </el-pagination>
    </el-card>
  </div>
</template>
  
  <script setup>
import { ref, onMounted, reactive, watch } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import axios from "axios";
import { Search } from "@element-plus/icons-vue";
import { Edit, Delete } from "@element-plus/icons-vue";
import { processOrder } from "@/utils/processData";

const router = useRouter();
const store = useStore();

// 列表请求相关参数
const tableForm = reactive({
  searchValue: "", // 搜索字段
  pageNo: 1, // 页码
  limit: 10, // 每页数据量
  sortField: "createdAt", // 排序字段
  sortOrder: "desc", // 默认降序desc [desc|asc]
});

// 搜索前的页码
const pageNoBeforeSearch = ref(1);
// 总数据量
const total = ref(0);
// 列表数据
const tableData = ref([]);

// 获取列表数据
const getTableData = async () => {
  await axios
    .get("/adminapi/product/listOfPage", { params: { ...tableForm } })
    .then((res) => {
      if (res?.data?.ActionType !== "OK") return;
      tableData.value = res.data.data.records; // 更新列表数据
      total.value = res.data.data.total; // 更新总记录数
    })
    .catch((error) => {
      console.error(error);
    });
};

// 处理页码变化
const handlePageChange = (page) => {
  tableForm.pageNo = page;
  if (tableForm.searchValue === "") pageNoBeforeSearch.value = page;
  getTableData();
};

// 处理每页数据量变化
const handleSizeChange = (limit) => {
  tableForm.limit = limit;
  getTableData();
};

// 排序
const changeTableSort = (column) => {
  if (column.order) {
    tableForm.sortOrder = processOrder(column.order);
  }
  if (column.prop) {
    tableForm.sortField = column.prop;
  }
  getTableData();
};

// 删除单条数据
const handleDelete = async (data) => {
  await axios
    .delete(`/adminapi/product/list/${data._id}`)
    .then((res) => {
      getTableData(); //tabledata 本地删除后重新刷新产品列表
    })
    .catch((error) => {
      console.error(error);
    });
};

// 搜索
const handleSearch = () => {
  getTableData();
};
watch(
  () => tableForm.searchValue,
  (newValue, oldValue) => {
    if (newValue === "") {
      tableForm.pageNo = pageNoBeforeSearch.value;
      getTableData();
    }
  }
);

// 编辑
const handleEdit = (item) => {
  router.push(`/product-manage/ProductEdit/${item._id}`);
};

onMounted(() => {
  getTableData();
});
</script>
  
<style lang="scss" scoped>
/*溢出省略号*/
.to-ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

:deep() {
  .el-pagination__rightwrapper {
    justify-content: center;
  }
  .el-card__body {
    height: 100%;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    gap: 20px;
  }
  .el-table {
    width: 100%;
    height: calc(100% - 105px);
    flex: 1;
  }
  .el-scrollbar__view {
    height: 100%;
  }
  .el-table__empty-block {
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .el-table__inner-wrapper:before {
    background-color: unset;
  }
}
.search-box {
  width: 100%;
  height: 35px;
  display: flex;
  justify-content: right;
  .search-icon {
    width: 16px;
    height: 16px;
    cursor: pointer;
    &:hover {
      color: var(--el-menu-active-color);
    }
  }
}
</style>